package com.example.movie.controller;

import com.example.movie.domain.R;
import com.example.movie.domain.User;
import com.example.movie.service.UserService;
import com.example.movie.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     *
     * @param user 用户信息
     * @return 返回注册结果
     */
    @PostMapping("/register")
    public R register(@RequestBody User user) {
        return userService.register(user);
    }

    /**
     * 用户登录
     *
     * @param user 用户信息
     * @param request HttpServletRequest
     * @return 返回登录结果
     */
    @PostMapping("/login")
    public R login(@RequestBody User user, HttpServletRequest request) {
        if(user.getName()==null||user.getPassword()==null){
            return R.error("用户名或密码不正确！");
        }
        return userService.login(user, request);
    }

    /**
     * 用户登出
     *
     * @param request HttpServletRequest
     * @return 返回登出结果
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        return userService.logout(request);
    }

    /**
     * 判断用户是否已登录
     *
     * @param request HttpServletRequest
     * @return 登录状态
     */
    @GetMapping("/isLogin")
    public Boolean isLogin(HttpServletRequest request) {
        return userService.isLogin(request);
    }

    /**
     * 返回当前登录用户信息
     * @param request
     * @return
     */
    @GetMapping("/info")
    public R getUserInfo(HttpServletRequest request) {
        return R.ok(UserUtil.getUserInfo(request));
    }

    /**
     * 更新用户信息(不要用来改密码)
     *
     * @param user 用户信息
     * @return 返回更新结果
     */
    @PostMapping("/update")
    public R update(@RequestBody User user) {
        return userService.update(user);
    }

    /**
     * 修改用户密码
     *
     * @param userId 用户ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return 返回修改结果
     */
    @PostMapping("/changePassword")
    public R changePassword(
            @RequestParam("userId") String userId,
            @RequestParam("oldPassword") String oldPassword,
            @RequestParam("newPassword") String newPassword) {
        long uidLong = Long.parseLong(userId);
        return userService.changePassword(uidLong, oldPassword, newPassword);
    }

}
